import { hash256 } from '@/utils/tools'
import sqlite3 from 'sqlite3'
export default {
    connections: {},
    db: null,
    init(dir) {
        this.connect(dir)
    },
    connect(dir) {
        const dbHash = hash256(dir)
        if (typeof this.connections[dbHash] === 'undefined') {
            const db = new sqlite3.Database(this.file(dir))
            this.connections[dbHash] = db
            this.db = db
        } else {
            this.db = this.connections[dbHash]
        }
        return this
    },
    file(dir) {
        return dir + '/.sd'
    },
    // 创建表格
    createFileTable() {
        return new Promise((resolve, reject) => {
            const tableSQL = `CREATE TABLE IF NOT EXISTS files (
                            hash TEXT PRIMARY KEY, 
                            path TEXT,
                            url TEXT,
                            total INTEGER,
                            upload INTEGER,
                            note TEXT
                            )`
            this.db.run(tableSQL)
            resolve()
        })
    },
    close() {
        for (let connect in this.connections) {
            this.connections[connect].close()
        }
        this.db = null
        this.connections = {}
    }
}
